package com.example.restatr.Atcivity.Charity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Charity.Bean.CharityDonateRecordBean;
import com.example.restatr.Atcivity.Charity.Bean.CharityHotBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CharityInfoAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private ImageView head;
    private TextView name;
    private TextView phone;
    private TextView bedsCountBoy;
    private TextView bedsCountGirl;
    private TextView address;
    private TextView workTime;
    private RecyclerView rv;
    private CardView btn;
    private CharityHotBean.RowsBean data;
    private TextView NumberDonors;
    private LinearLayout loading;
    private LinearLayout Null;
    private TextView nullText;
    private TextView bottomText;
    private int pageNum = 1;
    private List<CharityDonateRecordBean.RowsBean> rowsBeans = new ArrayList<>();
    private int total;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_charity_info_at);

        toolbar = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        head = findViewById(R.id.head);
        name = findViewById(R.id.name);
        phone = findViewById(R.id.phone);
        bedsCountBoy = findViewById(R.id.bedsCountBoy);
        bedsCountGirl = findViewById(R.id.bedsCountGirl);
        address = findViewById(R.id.address);
        workTime = findViewById(R.id.workTime);
        rv = findViewById(R.id.rv);
        btn = findViewById(R.id.btn);
        NumberDonors = findViewById(R.id.NumberDonors);
        loading = findViewById(R.id.loading);
        Null = findViewById(R.id.Null);
        nullText = findViewById(R.id.null_text);
        bottomText = findViewById(R.id.bottom_text);

        Tools.SetBarTitle(toolbar, barTitle, "公益详情", search, this, false);
        data = new Gson().fromJson(getIntent().getStringExtra("data"), new TypeToken<CharityHotBean.RowsBean>() {
        }.getType());

        Glide.with(this)
                .load(Tools.ip + data.getImgUrl())
                .transform(new RoundedCorners(15))
                .into(head);
        name.setText(data.getName());
        phone.setText(data.getAuthor());
        bedsCountBoy.setText("所需捐款：" + data.getMoneyTotal());
        bedsCountGirl.setText("已筹款数：" + data.getMoneyNow());
        address.setText(data.getActivityAt());
        workTime.setText(data.getType().getName());
        NumberDonors.setText("捐助人数：" + data.getDonateCount());
        nullText.setText("暂无捐助...");
        GetDonateRecord();
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!recyclerView.canScrollVertically(1) && newState == 0) {
                    if (rowsBeans.size() < total) {
                        pageNum++;
                        GetDonateRecord();
                    } else {
                        bottomText.setText("——到底了——");
                    }
                }
            }
        });
    }

    private void GetDonateRecord() {
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/public-welfare/donate-record/list?activityId=" + data.getId() + "&pageSize=10&pageNum=" + pageNum, MainActivity.sp.getString("token", ""));
            CharityDonateRecordBean charityDonateRecordBean = new Gson().fromJson(token, CharityDonateRecordBean.class);
            total = charityDonateRecordBean.getTotal();
            rowsBeans.addAll(charityDonateRecordBean.getRows());
            runOnUiThread(() -> {
                loading.setVisibility(View.GONE);
                if (rowsBeans.size() > 0) {
                    rv.setVisibility(View.VISIBLE);
                    rv.setAdapter(new adapter());
                } else {
                    Null.setVisibility(View.VISIBLE);
                }
            });
        }).start();
    }

    public void onClick(View view) {
        View inflate = getLayoutInflater().inflate(R.layout.dailog_layout, null);
        TextView title = inflate.findViewById(R.id.title);
        EditText ip1 = inflate.findViewById(R.id.ip1);
        EditText ip2 = inflate.findViewById(R.id.ip2);
        EditText ip3 = inflate.findViewById(R.id.ip3);
        EditText ip4 = inflate.findViewById(R.id.ip4);
        EditText dk = inflate.findViewById(R.id.dk);
        TextView unit = inflate.findViewById(R.id.unit);
        Button qd = inflate.findViewById(R.id.qd);
        title.setText("爱心捐助");
        ip2.setVisibility(View.GONE);
        ip3.setVisibility(View.GONE);
        ip4.setVisibility(View.GONE);
        dk.setVisibility(View.GONE);
        unit.setVisibility(View.VISIBLE);
        AlertDialog show = new AlertDialog.Builder(CharityInfoAt.this).setView(inflate).show();
        qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Tools.isEmptyText(ip1)) {
                    //发起捐助
                    new Thread(() -> {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("activityId", data.getId());
                            jsonObject.put("donateMoney", ip1.getText().toString());
                            String post = Tools.Post("/prod-api/api/public-welfare/donate-record", MainActivity.sp.getString("token", ""), jsonObject.toString());
                            JSONObject jx = new JSONObject(post);
                            String msg = jx.getString("msg");
                            int code = jx.getInt("code");
                            runOnUiThread(() -> {
                                Toast.makeText(CharityInfoAt.this, msg, Toast.LENGTH_SHORT).show();
                                if (code == 200) {
                                    rv.setVisibility(View.GONE);
                                    loading.setVisibility(View.VISIBLE);
                                    rowsBeans.clear();
                                    pageNum = 1;
                                    GetDonateRecord();
                                    data.setDonateCount(data.getDonateCount()+1);
                                    data.setMoneyNow(data.getMoneyNow()+Integer.valueOf(ip1.getText().toString()));
                                    NumberDonors.setText("捐助人数：" + data.getDonateCount());
                                    bedsCountGirl.setText("已筹款数：" + data.getMoneyNow());
                                    show.dismiss();

                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }).start();
                } else {
                    Toast.makeText(CharityInfoAt.this, "不能为空！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    class adapter extends RecyclerView.Adapter<adapter.viewHolder> {
        class viewHolder extends RecyclerView.ViewHolder {
            private ImageView head;
            private TextView name;
            private TextView date;
            private RatingBar score;
            private TextView level;
            private TextView content;
            private CardView reply;

            public viewHolder(@NonNull View itemView) {
                super(itemView);
                head = itemView.findViewById(R.id.head);
                name = itemView.findViewById(R.id.name);
                date = itemView.findViewById(R.id.date);
                score = itemView.findViewById(R.id.score);
                level = itemView.findViewById(R.id.level);
                content = itemView.findViewById(R.id.content);
                reply = itemView.findViewById(R.id.reply);

            }
        }

        @NonNull
        @Override
        public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = getLayoutInflater().inflate(R.layout.pj_list_item, parent, false);
            return new viewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull viewHolder holder, int position) {
            holder.head.setVisibility(View.GONE);
            holder.score.setVisibility(View.GONE);
            holder.level.setVisibility(View.GONE);
            holder.reply.setVisibility(View.GONE);
            holder.name.setText(rowsBeans.get(position).getUserName());
            holder.date.setText(rowsBeans.get(position).getCreateTime().substring(0, 10));
            holder.content.setText("捐助了" + rowsBeans.get(position).getDonateMoney() + "元");
        }

        @Override
        public int getItemCount() {
            return rowsBeans.size();
        }

    }

}